import React from 'react';
import PropTypes from 'prop-types';

class Mp3 extends React.Component {
  constructor(p) {
    super(p);
    this.action = this.action.bind(this);
    this.state = {
      url: this.props.url,
      type: this.props.type,
    };
  }

  action(type) {
    const map = {
      hide: () => {
        this.setState({
          type: 'hide',
        });
      },
      show: () => {
        this.setState({
          type: 'show',
        });
      },
    };
    return map[type];
  }

  render() {
    const type = this.state.type;

    if (type === 'hide') {
      return (
        <div>
          {this.state.url} &nbsp;&nbsp; <a onClick={this.action('show')}>展开</a>
        </div>
      );
    }

    return (
      <div>
        <audio controls="controls" autoPlay>
          <source src={this.state.url} type="audio/mpeg" />
          您的浏览器不支持mp3组件
        </audio>
        <a onClick={this.action('hide')}>收起</a>
      </div>
    );
  }
}

Mp3.propTypes = {
  url: PropTypes.string,
  type: PropTypes.bool,
};

Mp3.defaultProps = {
  type: 'hide',
};

export default Mp3;
